from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import os
from dotenv import load_dotenv
import requests
from openpyxl import Workbook
from io import BytesIO
import datetime

# 加载环境变量
load_dotenv()

app = Flask(__name__)
CORS(app)

# 配置智谱AI API
GML45_API_KEY = os.getenv('GML45_API_KEY', 'your-api-key-here')
GML45_API_BASE = os.getenv('GML45_API_BASE', 'https://open.bigmodel.cn/api/paas/v4')

# 语言代码到语言名称的映射
LANGUAGE_MAP = {
    'zh': '中文',
    'en': '英语',
    'ko': '韩语',
    'ja': '日语',
    'fr': '法语',
    'de': '德语',
    'es': '西班牙语',
    'ru': '俄语',
    'vi': '越南语',
    'ar': '阿拉伯语'
}

def translate_text(text, source_lang, target_lang):
    """
    使用智谱AI API翻译文本
    """
    try:
        # 构建翻译提示
        source_language = LANGUAGE_MAP.get(source_lang, '自动检测') if source_lang != 'auto' else '自动检测'
        target_language = LANGUAGE_MAP.get(target_lang, target_lang)
        
        prompt = f"""
        请将以下文本从{source_language}翻译成{target_language}。
        请保持原文的格式、换行和标点符号。
        只返回翻译结果，不要添加任何解释或额外内容。
        
        原文：
        {text}
        
        翻译结果：
        """
        
        # 调用智谱AI API
        headers = {
            "Authorization": f"Bearer {GML45_API_KEY}",
            "Content-Type": "application/json"
        }
        
        data = {
            "model": "glm-4.5",  # 使用智谱AI的GLM-4模型
            "messages": [
                {"role": "system", "content": "你是一个专业的翻译助手，专门进行多语言翻译。"},
                {"role": "user", "content": prompt}
            ],
            "temperature": 0.3,
            "max_tokens": 2000
        }
        
        response = requests.post(f"{GML45_API_BASE}/chat/completions",
                                headers=headers,
                                json=data,
                                timeout=30)
        
        if response.status_code != 200:
            print(f"API调用失败: {response.status_code}, {response.text}")
            if response.status_code == 429:
                return f"翻译失败: API余额不足或资源包已用完，请充值后重试"
            else:
                return f"翻译失败: API调用错误 (状态码: {response.status_code})"
        
        result = response.json()
        translated_text = result["choices"][0]["message"]["content"].strip()
        return translated_text
        
    except Exception as e:
        print(f"翻译错误: {e}")
        return f"翻译失败: {str(e)}"

@app.route('/translate', methods=['POST'])
def translate():
    """
    翻译API端点
    """
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({'error': '请求数据为空'}), 400
        
        text = data.get('text', '').strip()
        source_lang = data.get('sourceLang', 'auto')
        target_langs = data.get('targetLangs', [])
        
        if not text:
            return jsonify({'error': '翻译文本不能为空'}), 400
        
        if not target_langs:
            return jsonify({'error': '请选择至少一种目标语言'}), 400
        
        results = {}
        
        # 对每种目标语言进行翻译
        for target_lang in target_langs:
            translated_text = translate_text(text, source_lang, target_lang)
            results[target_lang] = translated_text
        
        return jsonify({
            'success': True,
            'results': results
        })
        
    except Exception as e:
        print(f"API错误: {e}")
        return jsonify({'error': f'服务器内部错误: {str(e)}'}), 500

@app.route('/export-excel', methods=['POST'])
def export_excel():
    """
    导出翻译结果为Excel文件
    """
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({'error': '请求数据为空'}), 400
        
        original_text = data.get('originalText', '').strip()
        translation_results = data.get('translationResults', {})
        
        if not original_text:
            return jsonify({'error': '原文不能为空'}), 400
        
        if not translation_results:
            return jsonify({'error': '翻译结果不能为空'}), 400
        
        # 创建Excel工作簿
        wb = Workbook()
        ws = wb.active
        ws.title = "翻译结果"
        
        # 设置表头
        headers = ['原文', '源语言']
        for lang_code, result in translation_results.items():
            lang_name = LANGUAGE_MAP.get(lang_code, lang_code)
            headers.append(f'{lang_name}翻译')
        
        ws.append(headers)
        
        # 获取源语言
        source_lang = data.get('sourceLang', 'auto')
        source_lang_name = LANGUAGE_MAP.get(source_lang, '自动检测') if source_lang != 'auto' else '自动检测'
        
        # 添加数据行
        row_data = [original_text, source_lang_name]
        for lang_code, result in translation_results.items():
            row_data.append(result)
        
        ws.append(row_data)
        
        # 调整列宽
        for col in ws.columns:
            max_length = 0
            column = col[0].column_letter  # 获取列字母
            for cell in col:
                try:
                    if len(str(cell.value)) > max_length:
                        max_length = len(str(cell.value))
                except:
                    pass
            adjusted_width = (max_length + 2) * 1.2
            ws.column_dimensions[column].width = adjusted_width
        
        # 保存到内存中的字节流
        excel_file = BytesIO()
        wb.save(excel_file)
        excel_file.seek(0)
        
        # 生成文件名（包含时间戳）
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"translation_results_{timestamp}.xlsx"
        
        return send_file(
            excel_file,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            as_attachment=True,
            download_name=filename
        )
        
    except Exception as e:
        print(f"Excel导出错误: {e}")
        return jsonify({'error': f'Excel导出失败: {str(e)}'}), 500

@app.route('/health', methods=['GET'])
def health_check():
    """
    健康检查端点
    """
    return jsonify({'status': 'healthy', 'message': 'GML4.5翻译服务运行正常'})

if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))
    debug = os.getenv('DEBUG', 'False').lower() == 'true'
    
    print(f"启动GML4.5翻译服务器在端口 {port}")
    print(f"调试模式: {debug}")
    
    app.run(host='0.0.0.0', port=port, debug=debug)